package com.sinosoft.cloud.access.handler;

import com.sinosoft.cloud.access.entity.TranData;
import com.sinosoft.cloud.access.limiting.CircuiBreaker;
import com.sinosoft.cloud.access.net.MessageObject;
import io.netty.channel.ChannelHandlerContext;

/**
 * cloud-netty
 *
 * @title: cloud-netty
 * @package: com.sinosoft.cloud.access.handler
 * @author: yangming
 * @date: 2017/12/3 上午10:56
 */
public class CircuitBreakerHandler extends AbstractHandler {


    /**
     * 处理限流
     *
     * @param messageObject
     * @return
     */
    @Override
    MessageObject dealMessage(ChannelHandlerContext ctx, MessageObject messageObject) {
        CircuiBreaker circuiBreaker = getCircuiBreaker();
        Boolean result = circuiBreaker.rateLimite();

        if (result){
            TranData errorTranData = new TranData();
            errorTranData.setHead(messageObject.getTranData().getHead());
            errorTranData.getHead().setFlag("1");
            errorTranData.getHead().setDesc("系统繁忙，请稍后再试！");
            messageObject.setTranData(errorTranData);
//            messageObject.setNext(MessageObject.Type.writeAndFlush);
            messageObject.setHasError(true);
        }

        return messageObject;
    }
}
